package com.tianyalei.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.tianyalei.model.GoodInfo;
import com.tianyalei.service.GoodInfoService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Created by wuwf on 17/7/11.
 */
@RestController
public class IndexController {
    @Resource(name = "db")
    private GoodInfoService goodInfoService;

    RateLimiter rateLimiter = RateLimiter.create(10);

    @RequestMapping("/qiang")
    public Object qiang(int count, String code) {
        if (goodInfoService.update(code, count) > 0) {
            return "购买成功";
        }
        return "购买失败";
    }

    @RequestMapping("/miaosha")
    public Object miaosha(int count, String code) {
        System.out.println("等待时间" + rateLimiter.acquire());
        if (goodInfoService.update(code, count) > 0) {
            return "购买成功";
        }
        return "购买失败";
    }

    /**
     * tryAcquire(long timeout, TimeUnit unit)
     * 从RateLimiter 获取许可如果该许可可以在不超过timeout的时间内获取得到的话，
     * 或者如果无法在timeout 过期之前获取得到许可的话，那么立即返回false（无需等待）
     */
    @RequestMapping("/buy")
    public Object miao(int count, String code) {
        //判断能否在1秒内得到令牌，如果不能则立即返回false，不会阻塞程序
        if (!rateLimiter.tryAcquire(1000, TimeUnit.MILLISECONDS)) {
            System.out.println("短期无法获取令牌，真不幸，排队也瞎排");
            return "失败";
        }
        if (goodInfoService.update(code, count) > 0) {
            System.out.println("购买成功");
            return "成功";
        }
        System.out.println("数据不足，失败");
        return "失败";
    }

    @RequestMapping("/add")
    public Object add() {
        for (int i = 0; i < 100; i++) {
            GoodInfo goodInfo = new GoodInfo();
            goodInfo.setCode("iphone" + i);
            goodInfo.setAmount(100);
            goodInfoService.add(goodInfo);
        }

        return "添加成功";
    }
}
